'use strict';
var express = require('express');
var router = express.Router();
var request = require('request');
var async = require('async');
var logger = require('../logger');
var superagent = require('superagent');
var jwt = require('jsonwebtoken');
var mongo = require('mongoskin');
var http = require("http");
var redis = require("redis");
var client = redis.createClient(6379,"127.0.0.1");


var db = mongo.db("mongodb://localhost:27017/course");
db.bind('course');


/**
 * 存课程
 * @param {*} req 
 * @param {*} res 
 * @param {*} next 
 */
function addCourse (req, res, next)
{
    var token = req.body.token;
    //TODO get course data
    var courseData = req.body.courseData;
    if(token){
        try{
            let decoded = jwt.verify(token, 'thefirstminappofvtmer');
            //TODO save course
                var username = decoded.username;
                let data = {};
                data.username = username;
                data.courseData = courseData;
                db.course.insert(data);
                res.send({ code:200, message:'ok' })
        }catch(err){
            res.send({ code: 401, message: 'token invid' + err });
        }
    }else {
        res.send({ code:402, message:'required token' });
    }
}
/**
 * 获取用户自添加课程
 * @param {*} req 
 * @param {*} res 
 * @param {*} next 
 */
function getAddCourse (req, res, next)
{
    var token = req.body.token;
    if(token){
        try{
            let decoded = jwt.verify(token, 'thefirstminappofvtmer');
            var username = decoded.username;
            var result = new Promise((resolve, reject) => {
                db.course.find({ 'username': username }).toArray( function(err, item){
                    resolve(item);
                });
            });
            var course = {};
            result.then(function(value){
                var course = value;
                if(course){
                    res.send({code:'200', message:'ok',data: course});
                }else{
                    res.send({code:'404', message:'Not Found'});
                }
            })
        }catch(err){
            res.send({ code: 401, message: 'token invid' + err })
        }
    }else{
        res.send({ code:'500', message:'token required' })
    }
}
/**
 *  修改自添加课程
 * @param {*} req 
 * @param {*} res 
 * @param {*} next 
 */
function editAddCourse(req, res, next)
{
    
    var token = req.body.token;
    var course = req.body.course;
    if(token){
        try{
            let decoded = jwt.verify(token, 'thefirstminappofvtmer');
            var username = decoded.username;
            //TODO update course

        }catch(err){
            res.send({ code: 401, message: 'token invid' + err })
        }
    }else{
        res.send({ code:'500', message:'token required' })
    }
}



module.exports = { addCourse, editAddCourse, getAddCourse};
